//
//  StapleCollectionViewCell.m
//  美食百科
//
//  Created by dllo on 16/1/24.
//  Copyright © 2016年 doll. All rights reserved.
//

#import "StapleCollectionViewCell.h"
#import "StapleTableViewCell.h"
#import "NewWorking.h"
#import "ClassModel.h"
#import "MJRefresh.h"
#import "Reachability.h"
@interface StapleCollectionViewCell()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)UITableView *stapleView;
@property(nonatomic,retain)NSMutableArray *stapleArray;
@property(nonatomic,assign)NSInteger rowNumber;
@end
@implementation StapleCollectionViewCell
- (void)dealloc
{[_urlStr release];
    [_stapleView release];
    [_stapleArray release];
    //[_itemArray release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
       // [self handle:self.row];
        //self.page = 1;
        self.stapleArray = [NSMutableArray array];
        self.stapleView = [[UITableView alloc]initWithFrame:self.bounds style:UITableViewStylePlain];
        self.stapleView.backgroundColor = [UIColor clearColor];

        __block StapleCollectionViewCell *staple = self;
        [self.stapleView addHeaderWithCallback:^{
            [staple refresh];
        }];
        [self.stapleView addFooterWithCallback:^{
            [staple refreshNumber];
        }];
        
        //上拉加载
        //self.stapleView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadAction)];
        NSLog(@"🍊");
        self.stapleView.dataSource = self;
        self.stapleView.delegate = self;
       // self.stapleView.bounces= NO ;
        self.stapleView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.stapleView.showsVerticalScrollIndicator = NO;
        [self.contentView addSubview:self.stapleView];
        [_stapleView release];
        self.stapleView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        [self.stapleView registerClass:[StapleTableViewCell class] forCellReuseIdentifier:@"stapleCellSecond"];
        
        
//        __block StapleCollectionViewCell *staple = self;
//        [self.stapleView addHeaderWithCallback:^{
////            NSInteger number = staple.page;
////            staple.page = 1;
//            staple.stapleArray = [NSMutableArray array];
//            [staple setRow:staple.row];
//            NSLog(@"🍎");
//            [staple.stapleView headerEndRefreshing];
//            [staple.stapleView reloadData];
//           // staple.page = number;
//        }];
//        
//        [self.stapleView addFooterWithCallback:^{
//             NSLog(@"🍊");
//             staple.page = staple.page+1;
//            NSLog(@"%ld",staple.page);
//            [self setRow:self.row];
//            [staple.stapleView footerEndRefreshing];
//            [staple.stapleView reloadData];
//        }];
        self.stapleView.headerPullToRefreshText = @"下拉刷新~";
        
        //下拉到一定程度时刷新显示的内容
        self.stapleView.headerReleaseToRefreshText = @"松开刷新~";
        
        //下拉松开后刷新显示的内容
        self.stapleView.headerRefreshingText = @"数据加载中~";
        self.stapleView.footerPullToRefreshText = @"上拉加载数据~";
        
        //上拉到一定程度后加载显示的内容
        self.stapleView.footerReleaseToRefreshText = @"松开加载数据~";
        
        //上拉松开后加载显示的内容
        self.stapleView.footerRefreshingText = @"数据加载中~";
    }
    return self;
}
-(void)refresh
{
    if (self.urlNumber) {
        self.urlStr = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods?kind=%@&value=%ld&sub_value=%ld&order_by=%ld&page=1&order_asc=%ld",self.kind,self.valueNumber,self.urlNumber,self.rowNumber+1,self.order_asc];
        
        NSLog(@"🍍%ld",self.page);
        NSLog(@"菠萝");
    }else{
        self.urlStr = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods?kind=%@&value=%ld&order_by=%ld&page=1&order_asc=%ld",self.kind,self.valueNumber,self.rowNumber+1,self.order_asc];
        NSLog(@"🍍%ld",self.page);
        
        NSLog(@"菠萝");
    }

    [NewWorking GetDayaWithURL:self.urlStr dic:nil sussess:^(id responseObject) {
         [self.stapleArray removeAllObjects];
        for (NSDictionary *dic in responseObject[@"foods"]) {
            ClassModel *classes = [[ClassModel alloc] init];
            
            [classes setValuesForKeysWithDictionary:dic];
            
            [self.stapleArray addObject:classes];
            [classes release];
        }
        
        // NSLog(@"🍍%@",self.stapleArray);
        
        [self.stapleView reloadData];
        [self.stapleView headerEndRefreshing];
        
    } filed:^(NSError *error) {
        NSLog(@"%@",error);
        [self.stapleView headerEndRefreshing];

    }];
    
}

-(void)refreshNumber
{
    if (self.urlNumber) {
        self.urlStr = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods?kind=%@&value=%ld&sub_value=%ld&order_by=%ld&page=%ld&order_asc=%ld",self.kind,self.valueNumber,self.urlNumber,self.rowNumber+1,self.stapleArray.count/20+1,self.order_asc];
        NSLog(@"🍍%ld",self.page);
        NSLog(@"菠萝");
    }else{
        self.urlStr = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods?kind=%@&value=%ld&order_by=%ld&page=%ld&order_asc=%ld",self.kind,self.valueNumber,self.rowNumber+1,self.stapleArray.count/20+1,self.order_asc];
        NSLog(@"%@",self.urlStr);
        NSLog(@"🍍%ld",self.page);
        
        NSLog(@"菠萝");
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        Reachability *reach = [Reachability reachabilityForInternetConnection];
        
        //如果无网络,弹窗提示
        if ( 0 == reach.currentReachabilityStatus){
            //弹窗提示
            UILabel *nonconnectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -50, self.bounds.size.width, 50)];
            nonconnectionLabel.textAlignment = NSTextAlignmentCenter;
            nonconnectionLabel.backgroundColor = [UIColor redColor];
            nonconnectionLabel.text = @"网络不给力,刷新试试~";
            nonconnectionLabel.textColor = [UIColor whiteColor];
            [self addSubview:nonconnectionLabel];
            
            //动画效果,通知栏缓慢出现
            [UIView animateWithDuration:0.6 animations:^{
                nonconnectionLabel.frame = CGRectMake(0, 0, self.bounds.size.width, 50);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.6 delay:3 options:UIViewAnimationOptionAutoreverse animations:^{
                    nonconnectionLabel.frame = CGRectMake(0, -50, self.bounds.size.width, 50);
                    [nonconnectionLabel release];
                    
                } completion:^(BOOL finished) {
                    
                }];
                
                //            [UIView animateWithDuration:1.9 animations:^{
                //                nonconnectionLabel.frame = CGRectMake(0, -50, kWidth, 50);
                //            //[nonconnectionLabel removeFromSuperview];
                //                [nonconnectionLabel release];
                //            }];
                
            }];
            
        }
    });

    
    [NewWorking GetDayaWithURL:self.urlStr dic:nil sussess:^(id responseObject) {
        if ([[NSString stringWithFormat:@"%ld",self.stapleArray.count/20+1] isEqualToString: responseObject[@"total_pages"]]) {
            return;
        }
        for (NSDictionary *dic in responseObject[@"foods"]) {
            ClassModel *classes = [[ClassModel alloc] init];
            
            [classes setValuesForKeysWithDictionary:dic];
            
            [self.stapleArray addObject:classes];
            [classes release];
        }
        
        // NSLog(@"🍍%@",self.stapleArray);
        
        [self.stapleView reloadData];
        [self.stapleView footerEndRefreshing];
        
    } filed:^(NSError *error) {
        NSLog(@"%@",error);
        [self.stapleView footerEndRefreshing];

    }];

}

//重写set方法
-(void)setRow:(NSInteger)row
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        Reachability *reach = [Reachability reachabilityForInternetConnection];
        
        //如果无网络,弹窗提示
        if ( 0 == reach.currentReachabilityStatus){
            //弹窗提示
            UILabel *nonconnectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -50, self.bounds.size.width, 50)];
            nonconnectionLabel.textAlignment = NSTextAlignmentCenter;
            nonconnectionLabel.backgroundColor = [UIColor redColor];
            nonconnectionLabel.text = @"网络不给力,刷新试试~";
            nonconnectionLabel.textColor = [UIColor whiteColor];
            [self addSubview:nonconnectionLabel];
            
            //动画效果,通知栏缓慢出现
            [UIView animateWithDuration:0.6 animations:^{
                nonconnectionLabel.frame = CGRectMake(0, 0, self.bounds.size.width, 50);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.6 delay:3 options:UIViewAnimationOptionAutoreverse animations:^{
                    nonconnectionLabel.frame = CGRectMake(0, -50, self.bounds.size.width, 50);
                    [nonconnectionLabel release];
                    
                } completion:^(BOOL finished) {
                    
                }];
                
                //            [UIView animateWithDuration:1.9 animations:^{
                //                nonconnectionLabel.frame = CGRectMake(0, -50, kWidth, 50);
                //            //[nonconnectionLabel removeFromSuperview];
                //                [nonconnectionLabel release];
                //            }];
                
            }];
            
        }
    });

    
    if (row == 0||_row != row) {
        self.rowNumber = row;
        if (row == 0) {
            self.order_asc = 0;
        }
        
    }
    
//    __block StapleCollectionViewCell *cell = self;
//    
//    cell.stapleView addHeaderWithCallback:^{
//        self
//    }
    
    //用外界传的数据判断每个cell的内容
    if (self.urlNumber) {
       self.urlStr = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods?kind=%@&value=%ld&sub_value=%ld&order_by=%ld&page=%ld&order_asc=%ld",self.kind,self.valueNumber,self.urlNumber,row+1,self.page,self.order_asc];
        NSLog(@"🍍%ld",self.page);
        NSLog(@"菠萝");
    }else{
        self.urlStr = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods?kind=%@&value=%ld&order_by=%ld&page=%ld&order_asc=%ld",self.kind,self.valueNumber,row+1,self.page,self.order_asc];
        NSLog(@"🍍%ld",self.page);

        NSLog(@"菠萝");
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        Reachability *reach = [Reachability reachabilityForInternetConnection];
        
        //如果无网络,弹窗提示
        if ( 0 == reach.currentReachabilityStatus){
            //弹窗提示
            UILabel *nonconnectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -50, self.bounds.size.width, 50)];
            nonconnectionLabel.textAlignment = NSTextAlignmentCenter;
            nonconnectionLabel.backgroundColor = [UIColor redColor];
            nonconnectionLabel.text = @"网络不给力,刷新试试~";
            nonconnectionLabel.textColor = [UIColor whiteColor];
            [self addSubview:nonconnectionLabel];
            
            //动画效果,通知栏缓慢出现
            [UIView animateWithDuration:0.6 animations:^{
                nonconnectionLabel.frame = CGRectMake(0, 0, self.bounds.size.width, 50);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.6 delay:3 options:UIViewAnimationOptionAutoreverse animations:^{
                    nonconnectionLabel.frame = CGRectMake(0, -50, self.bounds.size.width, 50);
                    [nonconnectionLabel release];
                    
                } completion:^(BOOL finished) {
                    
                }];
                
                //            [UIView animateWithDuration:1.9 animations:^{
                //                nonconnectionLabel.frame = CGRectMake(0, -50, kWidth, 50);
                //            //[nonconnectionLabel removeFromSuperview];
                //                [nonconnectionLabel release];
                //            }];
                
            }];
            
        }
    });

       [NewWorking GetDayaWithURL:self.urlStr  dic:nil sussess:^(id responseObject) {
        // NSLog(@"🍎%@",responseObject);
        
           [self.stapleArray removeAllObjects];
        for (NSDictionary *dic in responseObject[@"foods"]) {
            ClassModel *classes = [[ClassModel alloc] init];
            
            [classes setValuesForKeysWithDictionary:dic];
            
            [self.stapleArray addObject:classes];
            [classes release];
        }
        
        // NSLog(@"🍍%@",self.stapleArray);

        [self.stapleView reloadData];
        
        
        
    } filed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
        
        
    }

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.stapleArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    StapleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"stapleCellSecond"];
    cell.calory = self.rowNumber;
  //  NSLog(@"🌲%ld",self.row);
    cell.classModel  = self.stapleArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

  //  cell.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.contentView.frame.size.width/6+20;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    self.block(self.stapleArray[indexPath.row]);



}



@end
